<template>
  <div class="video">
    <div>
      <div class="title">
        <h1 style="color: #337ECC;font-size: 40px">企业-宣讲会</h1>
        <div>
          <PlaySquareOutlined class="icon"/>
          <VideoCameraAddOutlined class="icon"/>
        </div>

      </div>
    </div>
    <div style="border: 2px solid #337ECC; padding: 20px;border-top: 30px solid #337ECC; border-radius: 10px">

      <a-form
          ref="formRef"
          :label-col="labelCol"
          :model="formState"
          :rules="rules"
          :wrapper-col="wrapperCol"
      >
        <a-divider orientation="left">基本信息</a-divider>
        <a-row>
          <a-col :span="14">
            <a-form-item ref="videoName" :wrapperCol="{ span: 12 }" label="宣讲会名称" name="videoName">
              <a-input v-model:value="formState.videoName" :bordered="isBordered" :disabled="!isBordered" />
            </a-form-item>

            <a-form-item ref="videoStatus" :wrapperCol="{ span: 7 }" label="宣讲会状态" name="videoStatus">
              <a-select v-model:value="formState.videoStatus" :bordered="isBordered" :disabled="!isBordered"  placeholder="选择状态">
                <a-select-option value="开放">开放</a-select-option>
                <a-select-option value="关闭">关闭</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item ref="videoCertificationStatus" :wrapperCol="{ span: 8 }" label="审核-状态" name="videoCertificationStatus">
              <a-input v-model:value="formState.videoCertificationStatus" :bordered="isBordered"
                       :disabled="true"/>
            </a-form-item>

            </a-col>
          <div v-show="formState.videoCertificationStatus==='审核不通过'">
            <a-form-item ref="videoCertificationRefuse" label="拒绝原因"
                         name="videoCertificationRefuse">
              <a-textarea v-model:value="formState.videoCertificationRefuse"
                          :auto-size="{minRows: 3, maxRows: 20}"
                          show-count
                          style="width: 500px"
              />
            </a-form-item>
          </div>
          <a-col :span="12">
            <a-form-item ref="videoStartTime" :wrapperCol="{ span: 12 }" label="开始时间"
                         name="videoStartTime">
              <a-date-picker
                  :bordered="isBordered" :disabled="!isBordered"
                  show-time
                  v-model:value="formState.videoStartTime"
              />
            </a-form-item>
          </a-col>
            <a-col :span="12">
            <a-form-item ref="videoEndTime" :wrapperCol="{ span: 12 }" label="结束时间"
                         name="videoEndTime">
              <a-date-picker
                  :bordered="isBordered" :disabled="!isBordered"
                  show-time
                  v-model:value="formState.videoEndTime"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item ref="videoRemarks" label="补充信息"
                         name="videoRemarks">
              <a-textarea v-model:value="formState.videoRemarks"
                          :auto-size="{minRows: 3, maxRows: 20}"
                          show-count
                          :bordered="isBordered" :disabled="!isBordered"
                          style="width: 500px"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item ref="videoUrl" :wrapperCol="{ span: 12 }" label="宣讲会视频" name="videoUrl">
              <div v-if="isSave">
                <a-upload
                    v-model:fileList="fileList"
                    :disabled="!isBordered"
                    action="http://localhost:8080/video-file/video-upload"
                    name="file"
                    @change="handleChange"
                    @drop="handleDrop">
                  <div v-if="fileList.length<1" class="update">
                    <plus-outlined/>
                    <p class="ant-upload-text">单击或将文件拖到此区域以上传</p>
                    <p style="color: red">
                      仅支持上传一个mp4格式文件
                    </p>
                  </div>
                </a-upload>
              </div>
              <div v-else>
                <div style="display: flex ">

                  <video
                      ref="videoRef"
                      :autoplay="false"
                      :src="'http://localhost:8080/video-file/video?videoName='+formState.videoUrl"
                      controls
                      height="400"
                      style="margin-right: 10px; border: 1px solid red"
                      width="auto"
                      @timeupdate="handleTimeUpdate"
                  ></video>
                  <a-button v-if="isUpdate" @click="deleteVideo">删除</a-button>
                  <!--
                     src: 视频路径
                     width: 视频宽度
                     height: 视频高度
                     autoplay: 是否自动播放
                     controls: 是否显示控制条
                     @timeupdate: 视频播放时触发(获取视频播放的时间)
                   -->
                </div>
              </div>

            </a-form-item>

          </a-col>

          <a-col :span="24">
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
              <div>
                <div v-if="isSave&&!isUpdate">
                  <div style="display:flex;">
                    <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="save">
                      <a-button style="width:200px" type="primary">保存</a-button>
                    </a-popconfirm>
                    <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                      <a-button danger style="margin-left: 60px; width:200px" type="primary">重置</a-button>
                    </a-popconfirm>
                  </div>
                </div>
                <div v-else>
                  <div v-if="isUpdate" style="display:flex;">
                    <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="update">
                      <a-button style="width:200px" type="primary">保存</a-button>
                    </a-popconfirm>

                    <a-button style="margin-left: 60px; width:200px" @click="cancel">取消</a-button>

                    <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                      <a-button danger style="margin-left: 60px; width:200px" type="primary">重置</a-button>
                    </a-popconfirm>
                  </div>
                  <div v-else>
                    <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定修改吗？" @confirm="isupdate">
                      <a-button style="width:200px" type="primary">修改</a-button>
                    </a-popconfirm>

                    <a-button style="margin-left: 60px; width:200px" @click="goBack">返回</a-button>

                  </div>
                </div>
              </div>

            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import {h, onMounted, reactive, ref, toRaw} from 'vue';
import {useUserStore} from "@/stores/user.js";
import {queryInformationByUserIdAPI} from "@/apis/enterprise.js";
import {message, notification} from "ant-design-vue";
import {PlaySquareOutlined, PlusOutlined, SmileOutlined, VideoCameraAddOutlined} from "@ant-design/icons-vue";
import {addVideoAPI, queryVideoByEnterpriseUserIdAIP, updateVideoByIdAPI} from "@/apis/video.js";
import {useRouter} from "vue-router";
import moment from "moment";
import dayjs from "dayjs";

const formRef = ref();
const formState = reactive({
  videoStartTime: null,
  videoEndTime: null,
  videoRemarks:'',
  videoId: '',
  videoName: '',
  videoStatus: '',
  videoCertificationStatus:'',
  videoCertificationRefuse:'',
  videoUrl: '',
  videoUserId: '',
  videoEnterpriseId: '',
});
const rules = {
  videoRemarks:[
      {
        required: true,
        message: '请输入宣讲会补充信息！',
        trigger: 'change',
      },
  ],
  videoStartTime:[
      {
        required: true,
        message: '请输入宣讲会开始时间！',
        trigger: 'change',
      },
  ],
  videoEndTime:[
    {
      required: true,
      message: '请输入宣讲会结束时间！',
      trigger: 'change',
    },
  ],
  videoName: [
    {
      required: true,
      message: '请输入宣讲会名称！',
      trigger: 'change',
    },
  ],
  videoCertificationStatus: [
    {
      required: true,
    },
  ],

  videoStatus: [
    {
      required: true,
      message: '请选择宣讲会状态！',
      trigger: 'change',
    },
  ],
  videoText: [
    {
      required: true,
      message: '请输入宣讲会简介！',
      trigger: 'change',
    },
  ],
  videoUrl: [
    {
      required: true,
      message: '请上传视频！',
      trigger: 'change',
    },
  ],

};
const useStore = useUserStore();
const success = (msg) => {
  message.success(msg);
};
const save = () => {
  formRef.value
      .validate()
      .then(async () => {
        formState.videoUserId = useStore.userInfo.userId;
        formState.videoCertificationStatus = '审核中';
        const res = await addVideoAPI(formState);
        console.log(res);
        if (res.data.flag) {
          success(res.data.message);
          // 设置一个定时器，在1.5秒后刷新页面
          setTimeout(() => {
            window.location.reload();
          }, 1000); // 1500毫秒 = 1.5秒
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
const isUpdate = ref(false);//是否修改
const isBordered = ref(false);//是否边框
const isupdate = () => {//修改按钮
  if(formState.videoCertificationStatus === '审核中'){
    openNotification("宣讲会信息正在审核中,不可修改，请耐心等待！", "red", 'top');
  }else {
    isUpdate.value = true;
    isBordered.value = true;
    openNotification("点击照片或输入框均可修改！", "green", 'top');
  }
}
const update = () => {
  formRef.value
      .validate()
      .then(async () => {
        if(formState.videoStatus=== '开放'){
          formState.videoCertificationStatus = '审核中';
        }
        const res = await updateVideoByIdAPI(formState);
        console.log(res);
        if (res.data.flag) {
          if(formState.videoStatus=== '开放'){
            success("修改成功，请等待审核！");
            openNotification("已提交审核！", "#52C41A");
          }else {
            success("修改成功！");
          }

          // 设置一个定时器，在1.5秒后刷新页面
          setTimeout(() => {
            window.location.reload();
          }, 1000); // 1500毫秒 = 1.5秒
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
//重置后是否刷新
const isRefresh = ref(false);
const resetForm = () => {
  formRef.value.resetFields();
  isRefresh.value = true;
};

//控制按钮
const isSave = ref(true);
//获取数据
const enterpriseUserId = ref(useStore.userInfo.userId);
const getData = async (enterpriseUserId) => {
  //获取宣讲会信息
  const res = await queryInformationByUserIdAPI(enterpriseUserId.value);
  formState.videoEnterpriseId = res.data.data.enterpriseId;
  const res1 = await queryVideoByEnterpriseUserIdAIP(formState.videoEnterpriseId);
  if (res1.data.data == null) {
    formState.videoCertificationStatus = '未提交';
    isBordered.value = true
    isSave.value = true
    isUpdate.value = false;
  } else {
    isBordered.value = false
    isSave.value = false
    isUpdate.value = false;

    formState.videoId = res1.data.data.videoId;
    formState.videoName = res1.data.data.videoName;
    formState.videoStatus = res1.data.data.videoStatus;
    formState.videoStartTime = dayjs(res1.data.data.videoStartTime);
    formState.videoEndTime = dayjs(res1.data.data.videoEndTime);
    formState.videoRemarks = res1.data.data.videoRemarks;
    formState.videoCertificationStatus = res1.data.data.videoCertificationStatus;
    formState.videoCertificationRefuse = res1.data.data.videoCertificationRefuse;
    formState.videoUrl = res1.data.data.videoUrl;
    formState.videoUserId = res1.data.data.videoUserId;
    formState.videoEnterpriseId = res1.data.data.videoEnterpriseId;
  }

}


//生命周期
onMounted(() => {
  getData(enterpriseUserId);
});
const router = useRouter();
const goBack = () => {
  router.go(-1); // -1 表示返回上一个页面
}
const cancel = () => {
  isSave.value = false;
  isUpdate.value = false;
  isBordered.value = false;
  if (isRefresh.value) {
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);
  }
}
const fileList = ref([]);
const isUpload = ref(true);
const handleChange = info => {
  const status = info.file.status;
  if (status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} 文件上传成功！.`);
    console.log(fileList.value)
    formState.videoUrl = fileList.value[0].response.data;
    console.log(formState.videoUrl)
    isUpload.value = false;
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传失败！.`);
  }
};

const deleteVideo = () => {
  console.log("hello")
  formState.videoUrl=null;
  fileList.value=[];
  isSave.value=true;
}

//提示框
const openNotification = (des, col, placement) => {
  notification.open({
    message: '温馨提示！！！',
    description: des, placement,
    icon: () =>
        h(SmileOutlined, {
          style: {color: col},
        }),
  });
};




</script>
<style lang="scss" scoped>
.video {
  margin: 5px;
  padding: 20px 60px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 30px; /* 你可以调整这个值来改变圆角的大小 */

  .title {
    display: flex;
    justify-content: space-between;
    //border-bottom: 15px solid #4D7181;

    .icon {
      font-size: 35px;
      padding: 15px;
      color: white;
      margin-right: 20px;
      background-color: #C09E66;
      border-radius: 50px;
      margin-bottom: 10px;
    }
  }

  .update {
    height: 200px;
    width: 400px;
    display: flex;
    flex-direction: column; /* 垂直排列 */
    justify-content: center; /* 垂直居中 */
    align-items: center; /* 水平居中 */
    border: red 2px solid;

  }

}
</style>
